﻿
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using JulMar.Windows.Mvvm;
using MediaBrowser.Entities;
using MediaBrowser.Gui.MvvmUtils.UI;
using MediaBrowser.Gui.Tools;
using MediaBrowser.IServices;
using WPFMitsuControls;

namespace MediaBrowser.Gui.ViewModels
{
    /// <summary>
    /// View Model Page Books
    /// </summary>
    public class PageBooksViewModel : PageViewModelBase
    {
        public override string Name
        {
            get { return "Page Books"; }
        }

        private Book book;
        private ObservableCollection<string> lImgBook;
        private String formatedNavPage;
        private bool canSave;
        private String statusCanSave;
        private IOpenFileDialogVisualizer iOpenFileDialogVisualizer;

        #region Properties

        public ObservableCollection<string> LImgBook
        {
            get
            {
                return lImgBook;
            }
            set
            {
                lImgBook = value;
                OnPropertyChanged("LImgBook");
            }
        }

        public int CurrentSheetIndex
        {
            get
            {
                if (book != null)
                {
                    FormatedNavPage = "( " + book.CurrentSheetIndex + " sur " + Math.Floor((double)(book.Items.Count / 2)) + ") ";
                    return book.CurrentSheetIndex;
                }
                else
                {
                    FormatedNavPage = String.Empty;
                    return 1;
                }
            }
            set
            {
                if (book != null)
                {
                    book.CurrentSheetIndex = value;
                    FormatedNavPage = "( " + book.CurrentSheetIndex + " sur " + Math.Floor((double)(book.Items.Count / 2)) + ") ";
                    OnPropertyChanged("CurrentSheetIndex");
                }
            }
        }

        public String FormatedNavPage
        {
            get
            {
                return formatedNavPage;
            }
            set
            {
                formatedNavPage = value;
                OnPropertyChanged("FormatedNavPage");
            }
        }

        public bool CanSave
        {
            get
            {
                return this.canSave;
            }
            set
            {
                this.canSave = value;
                StatusCanSave = String.Empty;
                if (!canSave)
                {
                    StatusCanSave = "Veuillez renseigner tous les champs obligatoire";
                }
                OnPropertyChanged("CanSave");
            }
        }

        public String StatusCanSave
        {
            get
            {
                return this.statusCanSave;
            }
            set
            {
                this.statusCanSave = value;
                OnPropertyChanged("StatusCanSave");
            }
        }

        #endregion

        #region Command

        public ICommand BookOpenCommand
        {
            get;
            private set;
        }

        public ICommand BackwardPageCommand
        {
            get;
            private set;
        }

        public ICommand ForwardPageCommand
        {
            get;
            private set;
        }

        public ICommand PrepareAddBookCommand
        {
            get;
            private set;
        }

        public ICommand PrepareUpdateBookCommand
        {
            get;
            private set;
        }

        public ICommand ExploreFileCommand
        {
            get;
            private set;
        }

        public ICommand ClearFileCommand
        {
            get;
            private set;
        }

        public ICommand SaveBookCommand
        {
            get;
            private set;
        }

        public ICommand DeleteBookCommand
        {
            get;
            private set;
        }

        #endregion

        public PageBooksViewModel(IMediaManager service)
            : base(service)
        {
            LImgBook = new ObservableCollection<string>();
            Medias = new ObservableCollection<Media>(service.ListMediasByCategory(4));
            mediasView = CollectionViewSource.GetDefaultView(Medias);
            if (mediasView != null)
            {
                mediasView.CurrentChanged += mediasView_CurrentChanged;
            }

            BookOpenCommand = new DelegatingCommand<object>(BookOpen);
            BackwardPageCommand = new DelegatingCommand<Book>(BackwardPage);
            ForwardPageCommand = new DelegatingCommand<Book>(ForwardPage);

            PrepareAddBookCommand = new DelegatingCommand(PrepareAddBook);
            PrepareUpdateBookCommand = new DelegatingCommand(PrepareUpdateBook);
            ExploreFileCommand = new DelegatingCommand(ExploreFile);
            ClearFileCommand = new DelegatingCommand(ClearFile);
            DeleteBookCommand = new DelegatingCommand(DeleteBook);

            SaveBookCommand = new DelegatingCommand(SaveBook);

            iOpenFileDialogVisualizer = Resolve<IOpenFileDialogVisualizer>();
        }

        /// <summary>
        /// Appelé quand le média courant à changé
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void mediasView_CurrentChanged(object sender, System.EventArgs e)
        {
            OnPropertyChanged("CurrentMedia");
            CreateBook();
        }

        /// <summary>
        /// Transformation d'un fichier XPS en Image
        /// </summary>
        private void CreateBook()
        {
            using (new CustomWaitCursor())
            {
                try
                {
                    if (CurrentMedia != null)
                    {
                        string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\tmp\";
                        if (Directory.Exists(directory))
                        {
                            Directory.Delete(directory, true);
                        }

                        XPSConversion xps = new XPSConversion();
                        xps.SaveXpsPageToBitmap(CurrentMedia.UrlContent, directory);

                        LImgBook.Clear();
                        string[] files = Directory.GetFiles(directory);
                        for (int i = 0; i <= files.Length - 1; i++)
                        {
                            LImgBook.Add(files[i]);
                        }
                        OnPropertyChanged("CurrentSheetIndex");
                    }
                }
                catch (Exception ex)
                {
                    if (icustomMessageBoxVisualizer != null)
                    {
                        icustomMessageBoxVisualizer.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
        }

        /// <summary>
        /// Ouverture du composant Book
        /// </summary>
        /// <param name="b"></param>
        private void BookOpen(object b)
        {
            book = b as Book;
            OnPropertyChanged("CurrentSheetIndex");
        }

        /// <summary>
        /// Page précédente
        /// </summary>
        /// <param name="b"></param>
        private void BackwardPage(Book b)
        {
            book.AnimateToPreviousPage(true, 800);
            OnPropertyChanged("CurrentSheetIndex");
        }

        /// <summary>
        /// Page Suivante
        /// </summary>
        /// <param name="b"></param>
        private void ForwardPage(Book b)
        {
            book.AnimateToNextPage(true, 800);
            OnPropertyChanged("CurrentSheetIndex");
        }

        /// <summary>
        /// Préparation de l'ajout d'un Film
        /// </summary>
        private void PrepareAddBook()
        {
            CanSave = false;
            if (NewMedia != null)
            {
                NewMedia.PropertyChanged -= NewMedia_PropertyChanged;
            }
            NewMedia = new Media(0, String.Empty, DateTime.Now, null, null, null, null);
            NewMedia.PropertyChanged += NewMedia_PropertyChanged;
        }

        void NewMedia_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            CanSave = true;
            if ((String.IsNullOrEmpty(NewMedia.Name)) ||
                (String.IsNullOrEmpty(NewMedia.Description)) ||
                (String.IsNullOrEmpty(NewMedia.UrlContent)))
            {
                CanSave = false;
            }
        }

        /// <summary>
        /// Préparation de la modification d'un Livre
        /// </summary>
        private void PrepareUpdateBook()
        {
            CanSave = true;
            if (NewMedia != null)
            {
                NewMedia.PropertyChanged -= NewMedia_PropertyChanged;
            }
            NewMedia = (Media)CurrentMedia.Clone();
            NewMedia.PropertyChanged += NewMedia_PropertyChanged;
        }

        /// <summary>
        /// Choisir une fichier video associé au Livre
        /// </summary>
        private void ExploreFile()
        {
            if (iOpenFileDialogVisualizer != null)
            {
                String result = iOpenFileDialogVisualizer.ShowDialog("*.xps", "Fichier XPS (*.xps)|*.xps");
                NewMedia.UrlContent = result;
                OnPropertyChanged("NewMedia");
                NewMedia_PropertyChanged(null, null);
            }
        }

        /// <summary>
        /// Supprimer le fichier Video
        /// </summary>
        private void ClearFile()
        {
            NewMedia.UrlContent = String.Empty;
            OnPropertyChanged("NewMedia");
        }

        /// <summary>
        /// Ajout/Modification d'un Book
        /// </summary>
        private void SaveBook()
        {
            using (new CustomWaitCursor())
            {
                try
                {
                    #region Ajout
                    if (NewMedia.Id == 0)
                    {
                        Media resultMedia = service.SaveBook(NewMedia, null);
                        Medias.Add(resultMedia);
                        mediasView.MoveCurrentToLast();
                    }
                    #endregion

                    #region Modification
                    else
                    {
                        var media = (from m in Medias where m.Id == NewMedia.Id select m).Single<Media>();
                        var previousMedia = (from m in Medias where m.Id == NewMedia.Id select m).Single<Media>();
                        Media resultMedia = service.SaveBook(NewMedia, previousMedia);
                        previousMedia.Name = resultMedia.Name;
                        previousMedia.Description = resultMedia.Description;
                        previousMedia.UrlContent = resultMedia.UrlContent;
                        OnPropertyChanged("CurrentMedia");
                        mediasView.Refresh();
                    }
                    #endregion

                }
                catch (Exception ex)
                {
                    if (icustomMessageBoxVisualizer != null)
                    {
                        icustomMessageBoxVisualizer.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
        }

        /// <summary>
        /// Suppression d'un Book
        /// </summary>
        private void DeleteBook()
        {
            try
            {
                bool continu = true;
                if (icustomMessageBoxVisualizer != null)
                {
                    if (icustomMessageBoxVisualizer.Show("Etes-vous sûr de vouloir supprimer ce Livre ?", "Suppression", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
                    {
                        continu = false;
                    }
                }

                if (continu)
                {
                    service.DeleteBook(CurrentMedia);
                    Medias.Remove(CurrentMedia);
                }
            }
            catch (Exception ex)
            {
                if (icustomMessageBoxVisualizer != null)
                {
                    icustomMessageBoxVisualizer.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

        }
    }
}
